// pages/travel/detail/index.ts
import { travelApi } from '../../../utils/api';

Page({
  data: {
    recordId: 0,
    travelRecord: null as any,
    loading: false,
    markers: [] as any[],
  },

  onLoad(options: any) {
    const { id } = options;
    if (id) {
      this.setData({ recordId: parseInt(id) });
      this.loadTravelRecord(parseInt(id));
    }
  },

  onRetryLoad() {
    if (this.data.recordId > 0) {
      this.loadTravelRecord(this.data.recordId);
    }
  },

  async loadTravelRecord(id: number) {
    this.setData({ loading: true });
    console.log('开始加载旅游记录，ID:', id);

    try {
      const record: any = await travelApi.getDetail(id);
      console.log('✅ 加载的旅游记录数据:', record);
      console.log('✅ 开始日期:', record.start_date, '类型:', typeof record.start_date);
      console.log('✅ 结束日期:', record.end_date, '类型:', typeof record.end_date);
      console.log('✅ formatDate测试:', this.formatDate(record.start_date));
      
      this.setData({
        travelRecord: record,
      }, () => {
        console.log('✅ 数据设置完成，准备更新地图');
        console.log('✅ 设置后的travelRecord数据:', this.data.travelRecord);
        console.log('✅ 设置后的开始日期:', this.data.travelRecord.start_date);
        console.log('✅ 设置后的结束日期:', this.data.travelRecord.end_date);
        console.log('✅ 设置后的创建时间:', this.data.travelRecord.created_at);
        console.log('✅ formatDate函数测试:', this.formatDate(this.data.travelRecord.start_date));
        console.log('✅ formatDateTime函数测试:', this.formatDateTime(this.data.travelRecord.created_at));
        
        // 数据设置完成后更新地图
        this.updateMapMarkers();
      });
    } catch (error) {
      console.error('❌ 加载旅游记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    } finally {
      this.setData({ loading: false });
      console.log('✅ 加载完成，loading状态设置为false');
    }
  },


  onPreviewImage(e: any) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.travelRecord.images;
    wx.previewImage({
      current: images[index],
      urls: images,
    });
  },


  formatDate(dateString: string): string {
    if (!dateString) {
      return '未设置日期';
    }
    
    try {
      const date = new Date(dateString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '无效日期';
      }
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return '日期格式错误';
    }
  },

  formatDateTime(dateString: string): string {
    if (!dateString) {
      return '未设置时间';
    }
    
    try {
      const date = new Date(dateString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '无效时间';
      }
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      console.error('时间格式化错误:', error);
      return '时间格式错误';
    }
  },

  // 地图相关功能
  onOpenInMapApp() {
    const { travelRecord } = this.data;
    if (!travelRecord || !travelRecord.latitude || !travelRecord.longitude) {
      wx.showToast({
        title: '无法获取位置信息',
        icon: 'none',
      });
      return;
    }

    wx.openLocation({
      latitude: travelRecord.latitude,
      longitude: travelRecord.longitude,
      name: travelRecord.location || travelRecord.title,
      address: travelRecord.location || '旅行地点',
      scale: 18
    });
  },

  onNavigateTo() {
    const { travelRecord } = this.data;
    if (!travelRecord || !travelRecord.latitude || !travelRecord.longitude) {
      wx.showToast({
        title: '无法获取位置信息',
        icon: 'none',
      });
      return;
    }

    wx.openLocation({
      latitude: travelRecord.latitude,
      longitude: travelRecord.longitude,
      name: travelRecord.location || travelRecord.title,
      address: travelRecord.location || '旅行地点',
      scale: 18
    });
  },

  // 地图点击事件 - 打开大地图
  onMapTap() {
    const { travelRecord } = this.data;
    if (!travelRecord || !travelRecord.latitude || !travelRecord.longitude) {
      wx.showToast({
        title: '无法获取位置信息',
        icon: 'none',
      });
      return;
    }

    wx.openLocation({
      latitude: travelRecord.latitude,
      longitude: travelRecord.longitude,
      name: travelRecord.location || travelRecord.title,
      address: travelRecord.location || '旅行地点',
      scale: 18
    });
  },

  // 更新地图标记
  updateMapMarkers() {
    const { travelRecord } = this.data;
    if (!travelRecord || !travelRecord.latitude || !travelRecord.longitude) {
      return;
    }

    const markers = [{
      id: 1,
      latitude: travelRecord.latitude,
      longitude: travelRecord.longitude,
      title: travelRecord.location || travelRecord.title,
      iconPath: '/images/marker.png', // 可以使用默认标记
      width: 30,
      height: 30
    }];

    this.setData({
      markers
    });
  },

  // 监听数据变化，更新地图
  onTravelRecordChange() {
    this.updateMapMarkers();
  }
});
